//
//  TaskAlertViewController.m
//  HAODE
//
//  Created by LiYinDi on 15/12/30.
//  Copyright © 2015年 reabam.com. All rights reserved.
//

#import "TaskAlertViewController.h"
#import "TaskAlertTableViewCell.h"
#import "RDVTabBarController.h"
#import "HttpRequest.h"
#import "EGORefreshTableHeaderView.h"
@interface TaskAlertViewController ()<EGORefreshTableHeaderDelegate>
{
    NSUInteger _PageIndex;
    NSUInteger _TotalCount;
    NSUInteger _TotalPage;
    
    NSMutableArray *numArray;
    NSMutableArray *taskIDArray;
    NSMutableArray *memberNameArray;
    NSMutableArray *sourceArray;
    NSMutableArray *orderMoneyArray;
    NSMutableArray *depositMoneyArray;
    NSMutableArray *goodTypeArray;
    NSMutableArray *goodQualityArray;
    NSMutableArray *messageStatusArray;
    NSMutableArray *timeArray;
    
    EGORefreshTableHeaderView *_refreshHeaderView;
    BOOL _reloading;
    
    NSString *taskType;

}
@end

@implementation TaskAlertViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _dispatchCornerLabel.layer.cornerRadius=7.5;
    _dispatchCornerLabel.layer.masksToBounds=YES;
    _installCornerLabel.layer.cornerRadius=7.5;
    _installCornerLabel.layer.masksToBounds=YES;
    _finishedCornerLabel.layer.cornerRadius=7.5;
    _finishedCornerLabel.layer.masksToBounds=YES;
    numArray=[NSMutableArray array];
    memberNameArray=[NSMutableArray array];
    sourceArray=[NSMutableArray array];
    orderMoneyArray=[NSMutableArray array];
    depositMoneyArray=[NSMutableArray array];
    goodTypeArray=[NSMutableArray array];
    goodQualityArray=[NSMutableArray array];
    messageStatusArray=[NSMutableArray array];
    taskIDArray=[NSMutableArray array];
    timeArray=[NSMutableArray array];
    
    if (_refreshHeaderView == nil) {
        EGORefreshTableHeaderView *view = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - _listTableView.bounds.size.height, self.view.frame.size.width, _listTableView.bounds.size.height)];
        view.delegate = self;
        [_listTableView addSubview:view];
        _refreshHeaderView = view;
    
    }
    
    //  update the last update date
    [_refreshHeaderView refreshLastUpdatedDate];
    [self setNavigation];
    [self setAutoLayout];
    taskType=@"delivery";
    _PageIndex=0;
    [self loadMessageListNextPage:_PageIndex];
}
-(void) loadMessageListNextPage:(NSUInteger)oldPageNum {
    if(oldPageNum!=0 && _TotalCount<=numArray.count)
        return;
    if(oldPageNum == 0){
        [numArray removeAllObjects];
        [_listTableView reloadData];
    }
    _PageIndex=oldPageNum+1;
    [self requestServiceList: _PageIndex pageSize:20];
}
-(void)requestServiceList:(NSUInteger)pageIndex pageSize:(NSUInteger)pageSize
{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    if (Token ==nil) {
        Token=@"dd";
    }
    NSMutableDictionary *params = [NSMutableDictionary new];
    [params setValue:Token forKey:@"tokenId"];
    NSNumber *pageSizeNumber = [NSNumber numberWithInteger:pageSize];
    NSNumber *pageIndexNumber = [NSNumber numberWithInteger:pageIndex];
    [params setObject:pageSizeNumber forKey:@"PageSize"];
    [params setObject:pageIndexNumber forKey:@"PageIndex"];
    [params setObject:taskType forKey:@"taskType"];
    [Global showIndeterminateHud:@"加载中，请稍后。。。" delay:30 view:self.view];
    
    [HttpRequest requestData:@"MsgCenter/TaskRemind/List" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
        
          
        if (isSuccess) {
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
                _TotalCount=[[severDataDict.dataDict objectForKey:@"TotalCount"] integerValue];
                
                if (_TotalCount%20!=0) {
                    _TotalPage=_TotalCount/20+1;
                }
                else if (_TotalCount%20==0)
                {
                    _TotalPage=_TotalCount/20;
                }
                _dispatchCornerLabel.text=[NSString stringWithFormat:@"%d",[[severDataDict.dataDict objectForKey:@"dcount"] intValue]];
                 _installCornerLabel.text=[NSString stringWithFormat:@"%d",[[severDataDict.dataDict objectForKey:@"icount"] intValue]];
                 _finishedCornerLabel.text=[NSString stringWithFormat:@"%d",[[severDataDict.dataDict objectForKey:@"fcount"] intValue]];
                if ([_dispatchCornerLabel.text intValue]==0) {
                    _dispatchCornerLabel.hidden=YES;
                }
                if ([_installCornerLabel.text intValue]==0) {
                    _installCornerLabel.hidden=YES;
                }
                if ([_finishedCornerLabel.text intValue]==0) {
                    _finishedCornerLabel.hidden=YES;
                }
                NSMutableArray *mArray=[NSMutableArray arrayWithArray:[severDataDict.dataDict objectForKey:@"DataLine"]];
                
                //     NSLog(@"mOrderArray===%@",mOrderArray);
                if ( mArray.count>0) {
                    for (int i=0; i< mArray.count; i++) {
                        
                      
                        [numArray addObject:[[mArray objectAtIndex:i] objectForKey:@"orderNo"]];
                        [memberNameArray addObject:[[mArray objectAtIndex:i] objectForKey:@"memberName"]];
                        [sourceArray addObject:[[mArray objectAtIndex:i] objectForKey:@"source"]];
                        [orderMoneyArray addObject:[[mArray objectAtIndex:i] objectForKey:@"totalMoney"]];
                        [depositMoneyArray addObject:[[mArray objectAtIndex:i] objectForKey:@"earnestMoney"]];
                        [goodTypeArray addObject:[[mArray objectAtIndex:i] objectForKey:@"itemTypes"]];
                        [goodQualityArray addObject:[[mArray objectAtIndex:i] objectForKey:@"totalQuantity"]];
                        [messageStatusArray addObject:[[mArray objectAtIndex:i] objectForKey:@"taskStatus"]];
                        [timeArray addObject:[[mArray objectAtIndex:i] objectForKey:@"orderDate"]];
                        
                        [taskIDArray addObject:[[mArray objectAtIndex:i] objectForKey:@"trId"]];
                    }
                }
                
                [_listTableView reloadData];
                
            }else{
                [Global hideProgressHUDInternal:self.view];
                
            }
            
        }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            
            [Global showTextHudSub:@"连接失败" view:self.view];
        }
        
    }];
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return numArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 104;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * const  ServiceManagementIdentifier = @"SystemNotificatioanIdentifier";
    TaskAlertTableViewCell *cell=( TaskAlertTableViewCell *)[tableView dequeueReusableCellWithIdentifier: ServiceManagementIdentifier];
    if (cell==nil) {
        NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"TaskAlertTableViewCell" owner:self options:nil];
        cell = [array objectAtIndex:0];
        
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (numArray.count>0) {
        cell.numLabel.text=[numArray objectAtIndex:indexPath.row];
    }
    if (memberNameArray.count>0) {
        cell.memberNameLabel.text=[memberNameArray objectAtIndex:indexPath.row];
    }
    if (sourceArray.count>0) {
          cell.sourceNameLabel.text=[sourceArray objectAtIndex:indexPath.row];
    }
    if (timeArray.count>0) {
        NSString  *str = [timeArray objectAtIndex:indexPath.row];
        NSString *timeStr = [str substringToIndex:11];
        cell.timeLabel.text=[NSString stringWithFormat:@"%@",timeStr];
    }
    
    if (goodTypeArray.count>0) {
        cell.purchaseNameLabel.text=[NSString stringWithFormat:@"%@ 共%d件",[goodTypeArray objectAtIndex:indexPath.row],[[goodQualityArray objectAtIndex:indexPath.row] intValue]];
    }
    if (orderMoneyArray.count>0) {
        cell.priceLabel.text=[NSString stringWithFormat:@"%0.02f",[[orderMoneyArray objectAtIndex:indexPath.row] floatValue]];
    }
//    if (depositMoneyArray.count>0) {
//        cell.depositLabel.text=[NSString stringWithFormat:@"%0.02f",[[depositMoneyArray objectAtIndex:indexPath.row] floatValue]];
//    }
    if (messageStatusArray.count>0) {
        if ([[messageStatusArray objectAtIndex:indexPath.row] isEqualToString:@"Y"]) {
            cell.dotLabel.hidden=YES;
            [cell.numLabel setTextColor:[UIColor colorWithRed:153.0f/255.0f green:153.0f/255.0f blue:153.0f/255.0f alpha:1.0]];
             [cell.memberNameLabel setTextColor:[UIColor colorWithRed:153.0f/255.0f green:153.0f/255.0f blue:153.0f/255.0f alpha:1.0]];
             [cell.sourceNameLabel setTextColor:[UIColor colorWithRed:153.0f/255.0f green:153.0f/255.0f blue:153.0f/255.0f alpha:1.0]];
             [cell.timeLabel setTextColor:[UIColor colorWithRed:153.0f/255.0f green:153.0f/255.0f blue:153.0f/255.0f alpha:1.0]];
             [cell.purchaseNameLabel setTextColor:[UIColor colorWithRed:153.0f/255.0f green:153.0f/255.0f blue:153.0f/255.0f alpha:1.0]];
             [cell.priceLabel setTextColor:[UIColor colorWithRed:153.0f/255.0f green:153.0f/255.0f blue:153.0f/255.0f alpha:1.0]];
            
        }
        else
        {
             cell.dotLabel.hidden=NO;
            [cell.numLabel setTextColor:[UIColor colorWithRed:102.0f/255.0f green:102.0f/255.0f blue:102.0f/255.0f alpha:1.0]];
            [cell.memberNameLabel setTextColor:[UIColor colorWithRed:102.0f/255.0f green:102.0f/255.0f blue:102.0f/255.0f alpha:1.0]];
            [cell.sourceNameLabel setTextColor:[UIColor colorWithRed:102.0f/255.0f green:102.0f/255.0f blue:102.0f/255.0f alpha:1.0]];
            [cell.timeLabel setTextColor:[UIColor colorWithRed:102.0f/255.0f green:102.0f/255.0f blue:102.0f/255.0f alpha:1.0]];
            [cell.purchaseNameLabel setTextColor:[UIColor colorWithRed:102.0f/255.0f green:102.0f/255.0f blue:102.0f/255.0f alpha:1.0]];
            [cell.priceLabel setTextColor:[UIColor colorWithRed:102.0f/255.0f green:102.0f/255.0f blue:102.0f/255.0f alpha:1.0]];
        }
    }
    if (indexPath.row == [numArray count] - 1)
    {
        if (_PageIndex<=_TotalPage) {
            //  NSLog(@"###LOADING???");
            [self loadMessageListNextPage:_PageIndex];
        }
    }
    return cell;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    if (Token ==nil) {
        Token=@"dd";
    }
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:Token forKey:@"tokenId"];
    [param setValue:[taskIDArray objectAtIndex:indexPath.row] forKey:@"trId"];
    
    [Global showIndeterminateHud:@"加载中，请稍后。。。" delay:30 view:self.view];
    
    [HttpRequest requestData:@"MsgCenter/TaskRemind/Read" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
        
        if (isSuccess) {
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
                //  NSLog(@"sssss===%@",severDataDict.dataDict);
//                [Global showTextHudSub:[severDataDict.dataDict objectForKey:@"ResultString"] view:self.view];
//                NSIndexPath *indexPath1= [NSIndexPath indexPathForRow:indexPath.row inSection:0];
//                UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath1];
//                TaskAlertTableViewCell *taskCell=( TaskAlertTableViewCell *)cell;
//                taskCell.dotLabel.hidden=YES;
                [numArray removeAllObjects];
                [memberNameArray removeAllObjects];
                [sourceArray removeAllObjects];
                [orderMoneyArray removeAllObjects];
                [depositMoneyArray removeAllObjects];
                [goodTypeArray removeAllObjects];
                [goodQualityArray removeAllObjects];
                [messageStatusArray removeAllObjects];
                [timeArray removeAllObjects];
                [taskIDArray removeAllObjects];
                _PageIndex=0;
                [self loadMessageListNextPage:_PageIndex];
                
            }else{
                [Global hideProgressHUDInternal:self.view];
                
            }
            
        }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            
            [Global showTextHudSub:@"连接失败" view:self.view];
        }
        
    }];

}

- (IBAction)btnClick:(UIButton *)sender {
    for (int i=0; i<3; i++) {
        UIButton *btn=(UIButton *)[self.view viewWithTag:i+100];
        [btn setTitleColor:[UIColor colorWithRed:102.0f/255.0f green:102.0f/255.0f blue:102.0f/255.0f alpha:1.0] forState:UIControlStateNormal];
        
    }
     [sender setTitleColor:[UIColor colorWithRed:90.0/255.0 green:130.0/255.0 blue:26.0/255.0 alpha:1.0] forState:UIControlStateNormal];
    [_selectedLineLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(sender.mas_left) ;
        make.width.equalTo(_titleView.mas_width).dividedBy(3);
        
        make.height.equalTo(@1) ;
        make.top.equalTo(_titleView.mas_bottom).with.offset(-1) ;
    }];
    if (sender.tag==100) {
        taskType=@"delivery";
    }
    else if (sender.tag==101)
    {
        taskType=@"install";
    }
    else if (sender.tag==102)
    {
        taskType=@"finish";
    }

    [numArray removeAllObjects];
    [memberNameArray removeAllObjects];
    [sourceArray removeAllObjects];
    [orderMoneyArray removeAllObjects];
    [depositMoneyArray removeAllObjects];
    [goodTypeArray removeAllObjects];
    [goodQualityArray removeAllObjects];
    [messageStatusArray removeAllObjects];
    [timeArray removeAllObjects];
    [taskIDArray removeAllObjects];
    _PageIndex=0;
    [self loadMessageListNextPage:_PageIndex];
}
#pragma mark -
#pragma mark Data Source Loading / Reloading Methods

- (void)reloadTableViewDataSource{
    [numArray removeAllObjects];
    [memberNameArray removeAllObjects];
    [sourceArray removeAllObjects];
    [orderMoneyArray removeAllObjects];
    [depositMoneyArray removeAllObjects];
    [goodTypeArray removeAllObjects];
    [goodQualityArray removeAllObjects];
    [messageStatusArray removeAllObjects];
    [timeArray removeAllObjects];
    [taskIDArray removeAllObjects];
    _PageIndex=0;
    [self loadMessageListNextPage:_PageIndex];
    //  should be calling your tableviews data source model to reload
    //  put here just for demo
    _reloading = YES;
    
}

- (void)doneLoadingTableViewData{
    
    //  model should call this when its done loading
    _reloading = NO;
    [_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:_listTableView];
    
}


#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView==_listTableView) {
        [_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
    }
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if (scrollView==_listTableView) {
        [_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
    }
}


#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
    
    [self reloadTableViewDataSource];
    [self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:3.0];
    
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
    
    return _reloading; // should return if data source model is reloading
    
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
    
    return [NSDate date]; // should return date data source was last changed
    
}

-(void)setNavigation
{
    [[self rdv_tabBarController] setTabBarHidden:YES];
    
    self.navigationController.navigationBarHidden=NO;
        self.navigationController.navigationBar.barStyle = UIBaselineAdjustmentNone;
    UILabel *lineLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 43,ScreenWidth, 1)];
    [lineLabel setBackgroundColor:[UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1.0]];
    [self.navigationController.navigationBar addSubview:lineLabel];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setBarTintColor:Color];
    
    UIImage* backImage = [UIImage imageNamed:@"fanhui"];
    CGRect backframe = CGRectMake(0,0,30,30);
    UIButton* backButton= [[UIButton alloc] initWithFrame:backframe];
    [backButton setBackgroundImage:backImage forState:UIControlStateNormal];
    backButton.titleLabel.textAlignment=NSTextAlignmentLeft;
    [backButton addTarget:self action:@selector(BackAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    UILabel* titleLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, 0,40, 23)];
    titleLabel.text=@"任务提醒";
    titleLabel.font=[UIFont systemFontOfSize: 19];
    self.navigationItem.titleView=titleLabel;
 
}
-(void)BackAction:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)setAutoLayout
{
    
    [_titleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        
        make.height.equalTo(@50) ;
        
        make.top.equalTo(self.view.mas_top).with.offset(64) ;
    }];
    [_lineLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_titleView.mas_left);
        make.right.equalTo(_titleView.mas_right);
        
        make.height.equalTo(@1) ;
        make.top.equalTo(_titleView.mas_bottom).with.offset(-1) ;
    }];
    
    [_selectedLineLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_titleView.mas_left);
        make.width.equalTo(_titleView.mas_width).dividedBy(3);
        
        make.height.equalTo(@1) ;
        make.top.equalTo(_titleView.mas_bottom).with.offset(-1) ;
    }];

    [_dispatchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_titleView.mas_left);
        make.width.equalTo(_titleView.mas_width).dividedBy(3);
        
        make.height.equalTo(@48) ;
        make.top.equalTo(_titleView.mas_top) ;
    }];
    [_dispatchCornerLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_dispatchBtn.mas_centerX).with.offset(20);
        make.width.equalTo(@15);
        
        make.height.equalTo(@15) ;
        make.top.equalTo(_titleView.mas_top) .with.offset(6);
    }];
    [_installBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_dispatchBtn.mas_right);
        make.width.equalTo(_titleView.mas_width).dividedBy(3);
        
        make.height.equalTo(@48) ;
        make.top.equalTo(_titleView.mas_top) ;
    }];
    [_installCornerLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_installBtn.mas_centerX).with.offset(20);
        make.width.equalTo(@15);
        
        make.height.equalTo(@15) ;
        make.top.equalTo(_titleView.mas_top) .with.offset(6);
    }];

    [_finishedBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_installBtn.mas_right);
        make.width.equalTo(_titleView.mas_width).dividedBy(3);
        
        make.height.equalTo(@48) ;
        make.top.equalTo(_titleView.mas_top) ;
    }];
    [_finishedCornerLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_finishedBtn.mas_centerX).with.offset(20);
        make.width.equalTo(@15);
        
        make.height.equalTo(@15) ;
        make.top.equalTo(_titleView.mas_top) .with.offset(6);
    }];
    [_listTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        
        make.bottom.equalTo(self.view.mas_bottom) ;
        
        
        make.top.equalTo(_titleView.mas_bottom) ;
    }];

    
}

@end
